package com.naihe.anderson.sms.xml;

import java.io.File;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import org.xmlpull.v1.XmlSerializer;

import android.content.Context;
import android.util.Xml;

import com.naihe.anderson.sms.entity.SignatureMsg;
import com.naihe.anderson.sms.util.FileUtil;

public class SignatureXmlUtil {

	public static final String filePath = "signatureMsgInfo.xml";
	
	public List<SignatureMsg> getSignatureMsgByXml(Context context){
		File f = context.getFileStreamPath(filePath);  
        if(f.exists())
        {  
            SAXParserFactory factory = SAXParserFactory.newInstance();  
            try {  
                SAXParser sp = factory.newSAXParser();  
                SignatureXmlHandler handler = new SignatureXmlHandler();  
                sp.parse(f, handler);
                
                return handler.getSignatureMsgList();
            } catch(Exception e) {  
            	FileUtil.addLog("SignatureXmlUtil::getUserInfosByXml", SignatureXmlUtil.class, "SignatureXmlUtil", e);
            }  
        }  
        
        return new ArrayList<SignatureMsg>();
	}
	
	public void saveSignatureMsg(Context context, List<SignatureMsg> signatureMsgList){
		if(signatureMsgList == null)
			return;
		
		XmlSerializer serializer = Xml.newSerializer();
		StringWriter writer = new StringWriter();
		try{
			serializer.setOutput(writer);
			// <?xml version=”1.0″ encoding=”UTF-8″ standalone=”yes”?>
			serializer.startDocument("UTF-8",true);
		
			// <SignatureMsgss>
			serializer.startTag("","SignatureMsgList");

			for(SignatureMsg entitySignatureMsg: signatureMsgList){
				//<SignatureMsg signatureMsgId=”0000000″>
				serializer.startTag("","SignatureMsg");
				
				serializer.attribute("","signatureMsgId", entitySignatureMsg.getSignatureMsgId()+"");

				// <bodyMsg>qingzhi001</bodyMsg>
				serializer.startTag("", "bodyMsg");
				serializer.text(entitySignatureMsg.getBodyMsg());
				serializer.endTag("", "bodyMsg");
				
				// <contactNumbers>wuqh</contactNumbers>
				serializer.startTag("", "contactNumbers");
				serializer.text(entitySignatureMsg.getContactNumbersForSave());
				serializer.endTag("", "contactNumbers");
				
				// <signatureMsgStatut>wuqh</signatureMsgStatut>
				serializer.startTag("", "signatureMsgStatut");
				serializer.text(entitySignatureMsg.getSignatureMsgStatut()+"");
				serializer.endTag("", "signatureMsgStatut");
				
				// <signatureMsgTime>wuqh</signatureMsgTime>
				serializer.startTag("", "signatureMsgTime");
				serializer.text(entitySignatureMsg.getSignatureMsgTime()+"");
				serializer.endTag("", "signatureMsgTime");
				
				serializer.endTag("","SignatureMsg");
			}
			
			// </SignatureMsgList>
			serializer.endTag("", "SignatureMsgList");
			serializer.endDocument();
			write(writer.toString(), context);
		}catch (Exception e) {
			
		}
	}
	
	private boolean write(String txt,Context context)
	{
		try
		{
			OutputStream os = context.openFileOutput(filePath, Context.MODE_PRIVATE);
			OutputStreamWriter osw=new OutputStreamWriter(os);
			osw.write(txt);
			osw.close();
			os.close();
		}
		catch(Exception e)
		{
			return false;
		}
		return true;
	}
	
	private class SignatureXmlHandler extends DefaultHandler {

		List<SignatureMsg> signatureMsgs;
		private String tempString;
		private SignatureMsg signatureMsg;
		
		@Override
		public void startDocument() throws SAXException {
			signatureMsgs = new ArrayList<SignatureMsg>();
		}
		
		public List<SignatureMsg> getSignatureMsgList(){
			if(signatureMsgs == null)
				signatureMsgs = new ArrayList<SignatureMsg>();
			return signatureMsgs;
		}
		
		/** 
		 * sax 读取到元素节点的时候用到这个方法； 
		 */ 
		@Override
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {
			// 先判断读到的元素是否是UserInfo  
	        if ("SignatureMsg".equals(localName)) {  
	            // 如果读到的是UserInfo这个元素 就要保存起来，保存在我们创建的那个UserInfo的类中 所以我们要new一个UserInfo类  
	        	signatureMsg = new SignatureMsg();  
	            // attributes是属性。  
	        	signatureMsg.setSignatureMsgId(Long.parseLong(attributes.getValue("signatureMsgId")));
	        }
	        tempString = localName;
		}
		
		/** 
		 * sax 读取到文本节点的时候调用了这个方法 
		 */ 
		@Override
		public void characters(char[] ch, int start, int length)
				throws SAXException {
			if (signatureMsg != null) {  
	            String valueString = new String(ch, start, length);  
	            if ("bodyMsg".equals(tempString)) {  
	                // 如果当前解析到的节点是name 就要将name中的文本节点元素的值得到  
	            	signatureMsg.setBodyMsg(valueString);
	            } else if ("contactNumbers".equals(tempString)) {  
	            	signatureMsg.setContactNumbers(valueString);
	            } else if("signatureMsgStatut".equals(tempString)){
	            	signatureMsg.setSignatureMsgStatut(Integer.parseInt(valueString));
	            } else if("signatureMsgTime".equals(tempString)){
	            	signatureMsg.setSignatureMsgTime(Long.parseLong(valueString));
	            }
	        }
		}
		
		/** 
		 * 这个方法是每次遇到结束的标签都会执行的 并不是只遇到最后的结尾才调用 
		 *  
		 * 读取完毕遇到userInfo'的结尾 就将封装好的一个userInfobean保存到list中 并且清空userInfo对象 
		 *  
		 */
		@Override
		public void endElement(String uri, String localName, String qName)
				throws SAXException {
			if("SignatureMsg".equals(localName) && signatureMsg !=null)  
	        {  
				signatureMsgs.add(signatureMsg);
				signatureMsg = null;  
	        }  
	        tempString = null;
		}

		@Override
		public void endDocument() throws SAXException {
			// TODO Auto-generated method stub
			super.endDocument();
		}
	}
}
